package com.ruoyi.demowechatpay.service;


import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;

import com.github.binarywang.wxpay.service.impl.MerchantTransferServiceImpl;
import com.github.binarywang.wxpay.v3.util.RsaCryptoUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ruoyi.demowechatpay.pojo.dto.MyTransferCreateRequest;
import com.ruoyi.demowechatpay.pojo.dto.MyWxBatchesQueryRequest;
import com.ruoyi.demowechatpay.pojo.vo.MyBatchesQueryResult;
import com.ruoyi.demowechatpay.pojo.vo.MyTransferCreateResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * MyMerchantTransferServiceImpl
 *
 * @author huajiao
 * @date 2025/3/27 10:19
 */
@Slf4j
public class MyMerchantTransferServiceImpl extends MerchantTransferServiceImpl {

    private final WxPayService wxPayService;

    private static final Gson GSON = (new GsonBuilder()).create();

    public MyMerchantTransferServiceImpl(WxPayService wxPayService) {
        super(wxPayService);
        this.wxPayService = wxPayService;
    }

    public MyTransferCreateResult transferBills(MyTransferCreateRequest request) throws WxPayException {
        if (StringUtils.isEmpty(request.getAppid())) {
            request.setAppid(this.wxPayService.getConfig().getAppId());
        }

        String url = String.format("%s/v3/fund-app/mch-transfer/transfer-bills", this.wxPayService.getPayBaseUrl());
        RsaCryptoUtil.encryptFields(request, this.wxPayService.getConfig().getVerifier().getValidCertificate());

        String response = wxPayService.postV3WithWechatpaySerial(url, GSON.toJson(request));
        return GSON.fromJson(response, MyTransferCreateResult.class);
    }

    public MyBatchesQueryResult queryTransferBillNo(MyWxBatchesQueryRequest request) throws WxPayException {
        String url = String.format("%s/v3/fund-app/mch-transfer/transfer-bills/transfer-bill-no/%s",
                this.wxPayService.getPayBaseUrl(), request.getTransferBillNo());


        String response = wxPayService.getV3(url);
        return GSON.fromJson(response, MyBatchesQueryResult.class);
    }
}
